package com.neusoft.elmboot.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.neusoft.elmboot.Dto.AliPayReqDto;
import com.neusoft.elmboot.common.constant.AlipayConstant;
import com.neusoft.elmboot.common.result.Result;
import com.neusoft.elmboot.common.utils.AlipayUtil;
import com.neusoft.elmboot.po.OrdersEntity;
import com.neusoft.elmboot.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private OrdersService ordersService;


    @GetMapping("/pcPayment")
    public void pcPayment(AliPayReqDto aliPayReq, HttpServletResponse response) throws IOException {
        String payResultHtml = "支付失败啦！";
//
        try {
            payResultHtml = AlipayUtil.createPayOrder(aliPayReq.getOutTradeNo(),
                    aliPayReq.getTotalAmount(), aliPayReq.getSubject(), AlipayConstant.PC_PRODUCT_CODE);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        response.setContentType( "text/html;charset=UTF-8");
        response.getWriter().write(payResultHtml);
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * 手机网址支付
     * @param aliPayReq
     * @param response
     * @throws IOException
     */
    @GetMapping("/mobilePayment")
    public void mobilePayment(AliPayReqDto aliPayReq, HttpServletResponse response) throws IOException {
        String payResultHtml = "支付失败啦！";
//
        try {
            payResultHtml = AlipayUtil.createPayOrder(aliPayReq.getOutTradeNo(),
                    aliPayReq.getTotalAmount(), aliPayReq.getSubject(), AlipayConstant.MOBILE_PRODUCT_CODE);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        response.setContentType( "text/html;charset=UTF-8");
        response.getWriter().write(payResultHtml);
        response.getWriter().flush();
        response.getWriter().close();
    }


    @GetMapping("/returnUrl")
    @ResponseBody
    public String returnUrl(Map<String,Object> params) {
        return "同步回调成功";
    }

    @PostMapping("/notifyUrl")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request) throws AlipayApiException {
        //TODO： 1 验证签名
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号
        String out_trade_no = request.getParameter("out_trade_no");
        //支付宝交易号
        String trade_no = request.getParameter("trade_no");
        //交易状态
        String trade_status = request.getParameter("trade_status");

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayUtil.ALIPAY_PUBLIC_KEY, AlipayUtil.CHARSET, AlipayUtil.SIGN_TYPE);

        String ret = AlipaySignature.getSignCheckContentV1(params);
//        LogFile.logResult(ret);


        if(verify_result) {//验证成功


            OrdersEntity ordersEntity = ordersService.getById(out_trade_no);
            ordersEntity.setOrderState(1);
            ordersService.updateById(ordersEntity);




            return "success";
        } else {
            return "fail";
        }
    }

















    @ResponseBody
    @PostMapping("/createPayOrder")
    public Result createPayOrder(String outTradeNo,String totalAmount,String subject) {
        try {
            String payResultHtml = AlipayUtil.createPayOrder("TradeNo20240312001",
                    "100.5", "TCL热水壶", "http://localhost:8080/elm/showPayPage");
            /*AlipayClient alipayClient = AlipayUtil.getAlipayClient();
            AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
            request.setReturnUrl("http://your_return_url");
            request.setNotifyUrl("http://your_notify_url");
    
            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo("your_out_trade_no");
            model.setTotalAmount("your_total_amount");
            model.setSubject("your_subject");
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            request.setBizModel(model);
    
            AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
            if (response.isSuccess()) {
                return Result.success(response.getBody(), "创建支付订单成功");
            } else {
                return Result.fail(500, "创建支付订单失败");
            }*/
            return Result.success(payResultHtml);
        } catch (AlipayApiException e) {
            return Result.error("创建支付订单失败");
        }
    }

    /**
     * 支付宝同步回调方法
     * @param request
     * @param response
     */
    @GetMapping("/showPayPage")
    public void showPayPage(HttpServletRequest request,HttpServletResponse response) {
        try {
            // 获取支付宝支付回调参数
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
                String name = entry.getKey();
                String[] values = entry.getValue();
                StringBuilder valueStr = new StringBuilder();
                for (String value : values) {
                    valueStr.append(value).append(",");
                }
                valueStr.deleteCharAt(valueStr.length() - 1);
                params.put(name, valueStr.toString());
            }
            System.out.println("-----/showPayPage：支付宝回调参数如下：");
            System.out.println(params);
            StringBuilder msgSB = new  StringBuilder("<h1>------恭喜支付成功！----</h1>");
            msgSB.append("<h2>支付宝返回的同步通知回调信息如下：</h2>");
            Set ketSet=params.keySet();
            for(Object key:ketSet){
                msgSB.append("<p>"+key);
                Object values=params.get(key);
                msgSB.append(":"+values+"</p>");
            }

            response.setContentType( "text/html;charset=UTF-8");
            response.getWriter().write(msgSB.toString());
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 支付宝异步回调方法
     * @param request
     * @param response
     * @throws IOException
     */
    @PostMapping("/alipayCallback")
    public void alipayCallback(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // 获取支付宝支付回调参数
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : requestParams.entrySet()) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            StringBuilder valueStr = new StringBuilder();
            for (String value : values) {
                valueStr.append(value).append(",");
            }
            valueStr.deleteCharAt(valueStr.length() - 1);
            params.put(name, valueStr.toString());
        }
        System.out.println("-----/alipayCallback---支付宝回调参数如下：");
        System.out.println(params);

        // 验证支付宝回调签名
        boolean verifyResult = AlipayUtil.verify(params);
        if (verifyResult) {
            // 验证通过，处理自己的业务逻辑
            String tradeStatus = params.get("trade_status");
            if (tradeStatus.equals("TRADE_SUCCESS") || tradeStatus.equals("TRADE_FINISHED")) {
                // 支付成功，处理订单逻辑
                // ... 自己的业务逻辑 ...

                // 返回成功响应给支付宝
                response.getWriter().println("success");
            } else {
                // 支付失败
                // ... 处理支付失败逻辑 ...

                // 返回失败响应给支付宝
                response.getWriter().println("failure1");
            }
        } else {
            // 验证失败，打印日志等处理
            // ... 处理验签失败逻辑 ...

            // 返回失败响应给支付宝
            response.getWriter().println("failure2");
        }
    }
}
